# 保存最后N个元素
# 在迭代或是其他形式的处理过程中，对最后几项记录做一个有限的历史记录统计
from collections import deque


def search(lines, pattern, history=5):
    previous_lines = deque(maxlen=history)
    for line in lines:
        if pattern in line:
            yield line, previous_lines
        previous_lines.append(line)


if __name__ == '__main__':
    with open("E:\\python_learning\\code\\python-cookbook-code\\Chapter1\\test.txt", encoding="utf-8") as f:
        for line, prevlines in search(f, 'python', 5):
            for pline in prevlines:
                print(pline, end='')
            print(line, end='')
            print('-'*20)



